package com.cairh.xpe.context.action;

import com.cairh.xpe.core.annotation.NoLogin;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ConditionalOnProperty(value = "xpe.error.enable", havingValue = "true", matchIfMissing = true)
@Controller
@RequestMapping("/error")
@NoLogin
public class CommonErrorController extends AbstractErrorController {
    public CommonErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }
    @RequestMapping
    public ModelAndView handleError(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus httpStatus = getStatus(request);
        int code = httpStatus.value();
        switch (code){
            case 400:
                return new ModelAndView("400");
            case 403:
                return new ModelAndView("403");
            case 404:
                return new ModelAndView("404");
            case 500:
                return new ModelAndView("500");
            case 502:
                return new ModelAndView("502");
            default:
                return new ModelAndView("500");
        }
    }
    @Override
    public String getErrorPath() {
        return "/error";
    }
    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        }
        catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
